import 'dart:ui';

import 'package:flame/components.dart';
import 'package:flutter/material.dart' hide Image;
import 'package:flutter_fireworks/fire/firework_effect.dart';

import 'explosion.dart';

class Firework extends PositionComponent with HasGameReference<FireworkEffect> {
  final double firecrackerSize = 9;
  final Firecracker firecracker;
  final double imageY;
  Image? _image;

  Firework(this.firecracker):
        imageY = firecracker.y,
        super(anchor: Anchor.center);


  @override
  void onLoad() async {
    const AssetImage("images/3.0x/firework.png")
        .resolve(ImageConfiguration.empty)
        .addListener(
          ImageStreamListener(
            (imageInfo, syncCall) {
              _image = imageInfo.image;
            },
          ),
        );
    super.onLoad();
  }

  @override
  void update(double dt) {
    // 花炮上升，速度逐渐减慢（模拟重力影响）
    double progress = 1 - (firecracker.y / 1920 * 1.1);
    double speed = 8 * (1 - progress * 0.8);
    double newY = firecracker.y - speed;
    firecracker.trail.insert(0, Offset(firecracker.x, firecracker.y));
    while (firecracker.trail.length > 30) {
      firecracker.trail.removeAt(30);
    }
    if (newY <= firecracker.targetY) {
      newY = firecracker.targetY;
      final particles = game.createParticleList(firecracker.x, newY, firecracker.color);
      game.world.add(Explosion(firecracker, particles));
      firecracker.y = newY;
      firecracker.isExploding = true;
      game.world.remove(this);
    } else {
      firecracker.y = newY;
    }
  }

  @override
  void render(Canvas canvas) {
    Paint paintLine = Paint()..strokeWidth = 4;
    Paint paintFire = Paint()..color = firecracker.color;
    Paint paintFireAlpha = Paint()..color = firecracker.color.withValues(alpha: 0.5);
    if (!firecracker.isExploding && !firecracker.isFinished && firecracker.trail.length > 1) {
      for (int i = 0; i < firecracker.trail.length - 1; i++) {
        double alpha = 1 - (i / firecracker.trail.length) * 0.8;
        paintLine.color = firecracker.color.withValues(alpha: alpha);
        canvas.drawLine(firecracker.trail[i], firecracker.trail[i + 1], paintLine);
      }
      canvas.drawCircle(Offset(firecracker.x, firecracker.y), firecrackerSize, paintFire);
      canvas.drawCircle(Offset(firecracker.x, firecracker.y), firecrackerSize * 1.5, paintFireAlpha);
      // canvas.save();
      if (_image != null) {
        canvas.scale(0.5);
        canvas.drawImage(
          _image!,
          Offset(
            firecracker.x * 2 - _image!.width / 4 - 65,
            imageY * 2 - _image!.height / 4 - 200,
          ),
          Paint(),
        );
      }
    }
  }

}
